﻿using Mengsk.ProxyDelivery.App.Device;
using Mengsk.ProxyDelivery.App.UI;
using Mengsk.ProxyDelivery.App.UI.Order;
using Mengsk.ProxyDelivery.Domain;
using Mengsk.ProxyDelivery.Service;
using mshtml;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Speech.Synthesis;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Mengsk.ProxyDelivery.App.UI.Delivery
{
    /// <summary>
    /// DeliveryScanUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class DeliveryScanUserControl : UserControl, IPlugin
    {
        private bool myLoaded = false;
        private IDevice device = null;
        private OrderService orderRepertory = ServiceContainer.GetService<OrderService>();
        SpeechSynthesizer synth = new SpeechSynthesizer();
        private System.Collections.ObjectModel.ObservableCollection<DeliveryScanViewModel> scanedViewModels = new System.Collections.ObjectModel.ObservableCollection<DeliveryScanViewModel>();

        public string Title
        {
            get { return "发货扫描"; }
        }

        public Control UIControl
        {
            get { return this; }
        }

        public DeliveryScanUserControl()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.myLoaded)
            {
                return;
            }
            this.wb1.Navigate("http://jingang.yto56.com.cn/ord/logout.action");
            this.wb1.Navigating += wb1_Navigating;
            this.wb1.LoadCompleted += wb1_LoadCompleted;
            this.dgvScanedItems.ItemsSource = this.scanedViewModels;
            try
            {
                string type = LocalConfigService.GetValue("WEIGHT_DEVICE", "");
                if (type == null)
                {
                    throw new Exception("未设置称重设备");
                }
                Type t = Type.GetType(type, true);
                this.device = Activator.CreateInstance(t) as IDevice;
                if (this.device == null)
                {
                    throw new Exception("无法创建指定的称重设备:" + type);
                }
                myLoaded = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "打开设备失败");
            }
        }

        private void wb1_LoadCompleted(object sender, NavigationEventArgs e)
        {
            try
            {
                this.btnInject.IsEnabled = true;
                string filePath = System.IO.Path.Combine(App.DIR_PLUGIN, "YTInject.js");
                string content = System.IO.File.ReadAllText(filePath);

                HTMLDocument doc2 = this.wb1.Document as HTMLDocument;
                IHTMLElementCollection nodes = doc2.getElementsByTagName("head");
                IHTMLScriptElement injectNode = (IHTMLScriptElement)doc2.createElement("SCRIPT");
                injectNode.type = "text/javascript";
                injectNode.text = content;

                foreach (IHTMLElement elem in nodes)
                {
                    HTMLHeadElement head = (HTMLHeadElement)elem;
                    head.appendChild((IHTMLDOMNode)injectNode);
                    head.appendChild((IHTMLDOMNode)injectNode);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "页面加载完成，无法注入JS代码");
            }
        }

        private void wb1_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            this.btnInject.IsEnabled = false;
        }

        private void tbDeliveryNumber_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter)
            {
                return;
            }
            e.Handled = true;

            this.tbResult.Text = "请扫描条码";
            this.tbResultWeight.Text = "0 KG";
            this.tbResult.Background = null;
            try
            {
                string number = this.tbDeliveryNumber.Text.Trim().ToUpper();
                if (string.IsNullOrWhiteSpace(number))
                {
                    return;
                }
                double weight = 0;
                if (this.chkEnableInput.IsChecked.Value)
                {
                    try
                    {
                        weight = float.Parse(this.tbWeight.Text.Trim());
                    }
                    catch
                    {
                        MessageBox.Show("你开启的手动输入重量，但输入值不正确");
                        return;
                    }
                }
                else
                {
                    this.tbWeight.Text = "";
                    weight = this.device.ReadWeight();
                }

                if (weight <= 0)
                {
                    throw new Exception("重量不能小于0");
                }

                this.tbResultWeight.Text = weight.ToString("F2") + "KG";
                this.tbWeight.Text = weight.ToString("F2");
                var order = this.orderRepertory.MarkDelivery(number, weight, this.chkIngorePopError.IsChecked.Value, this.chkIngoreWeightDetect.IsChecked.Value);

                if (order == null)
                {
                    throw new Exception("订单不存在");
                }

                //如果是货到付款，则标记圆通PPCOD
                if (order.PopPayType == OrderPopPayType.COD)
                {
                    if (string.IsNullOrWhiteSpace(order.PopCodNumber) && string.IsNullOrWhiteSpace(order.PopOrderId))
                    {
                        throw new Exception("订单为货到付款，但COD编号与平台编号都为空");
                    }

                    string codNumber = order.PopCodNumber.Trim().Replace(" ", "").Replace(":", "").Replace("：", "");

                    if (string.IsNullOrWhiteSpace(codNumber))
                    {
                        try
                        {
                            codNumber = this.orderRepertory.GetOrderPopCodNumber(order.Id, order.PopShopId, order.PopOrderId);
                        }
                        catch (Exception ex)
                        {
                            this.AppendText("获取PPCOD失败:" + order.PopCodNumber + "," + order.PopShopId + ex.Message);
                        }
                    }

                    if (string.IsNullOrWhiteSpace(codNumber))
                    {
                        try
                        {
                            codNumber = this.orderRepertory.GetOrderPopCodNumber(order.Id, order.PopShopId, order.PopOrderId);
                        }
                        catch (Exception ex)
                        {
                            this.AppendText("获取PPCOD失败:" + order.PopCodNumber + "," + order.PopShopId + ex.Message);
                        }
                    }


                    if (string.IsNullOrWhiteSpace(codNumber))
                    {
                        throw new Exception("获取PPCOD失败");
                    }

                    //获取物流编号
                    string deliveryId = this.QueryOrderId(codNumber);

                    if (string.IsNullOrWhiteSpace(deliveryId) || deliveryId.Length < 8)
                    {
                        deliveryId = this.QueryOrderId(codNumber);
                    }

                    //获取失败，尝试从网络更新ppcod再次获取
                    if (string.IsNullOrWhiteSpace(deliveryId) || deliveryId.Length < 8)
                    {
                        this.tbYTDebug.AppendText(DateTime.Now + ":第一次获取物流编号失败,获取到的数据:" + deliveryId);
                        if (order.PopShopId > 0 && String.IsNullOrWhiteSpace(order.PopOrderId) == false)
                        {
                            //从网络获取ppcod
                            string codNumber1 = this.orderRepertory.GetOrderPopCodNumber(order.Id, order.PopShopId, order.PopOrderId);
                            if (string.IsNullOrWhiteSpace(codNumber1))
                            {
                                throw new Exception("获取物流号失败:订单COD编号:" + codNumber + ",网络获取的Cod编号:" + codNumber1);
                            }
                            codNumber = codNumber1;
                            deliveryId = this.QueryOrderId(codNumber);
                            if (string.IsNullOrWhiteSpace(deliveryId) || deliveryId.Length < 8)
                            {
                                deliveryId = this.QueryOrderId(codNumber);
                            }
                        }
                        else
                        {
                            this.tbYTDebug.AppendText("从网络更新Cod失败，当前信息:" + order.PopShopId + "," + order.PopOrderId);
                            throw new Exception("从网络更新数据失败，因为店铺编号为空或者平台编号为空");
                        }
                    }

                    if (string.IsNullOrWhiteSpace(deliveryId) || deliveryId.Length < 8)
                    {
                        this.tbYTDebug.AppendText(DateTime.Now + ":最终获取物流编号失败,获取到的数据:" + deliveryId);
                        throw new Exception("最终获取物流编号失败");
                    }

                    object ret = this.wb1.InvokeScript("mengsk_markdelivery", deliveryId, number);
                    if (ret == null)
                    {
                        throw new Exception("发货标记失败,JS返回值为空");
                    }

                    string strRet = ret.ToString();
                    if (strRet.Equals("SUCCESS", StringComparison.OrdinalIgnoreCase) == false)
                    {
                        this.AppendText("标记发货失败:" + strRet);
                        throw new Exception("标记发货失败:");
                    }
                }

                this.tbResult.Text = "允许发货";
                this.synth.Speak("允许发货");
                this.lstItems.ItemsSource = order.OrderGoodss;
                this.spReceiver.DataContext = order;


                var first = this.scanedViewModels.FirstOrDefault(obj => obj.OrderId == order.Id.ToString());
                if (first != null)
                {
                    this.scanedViewModels.Remove(first);
                }

                //生成记录
                DeliveryScanViewModel svm = new DeliveryScanViewModel
                {
                    DeliveryCompany = order.DeliveryCompany,
                    DeliveryNumber = number,
                    OrderId = order.Id.ToString(),
                    SellerId = order.SellerId.ToString(),
                    Time = DateTime.Now,
                    Weight = weight,
                    ReceiverInfo = order.ReceiverName + "," + order.ReceiverPhone + "," + order.ReceiverMobile + "," + order.ReceiverAddress,
                };

                if (order.OrderGoodss != null)
                {
                    svm.OrderGoodsInfo = String.Join(",", order.OrderGoodss.Select(obj => obj.Vendor + " " + obj.Number + " " + obj.Color + " " + obj.Size + " " + obj.Count + ("件")).ToArray());
                }
                this.scanedViewModels.Add(svm);

                //更新发货物流
                this.tbTotal.Text = this.scanedViewModels.Count.ToString();
                var count = this.scanedViewModels.GroupBy(obj => obj.DeliveryCompany).ToArray();
                string message = string.Join(",", count.Select(obj => obj.Key + ": " + obj.Count()));
                this.tbTotal.Text = "共 " + this.scanedViewModels.Count.ToString() + "  " + message;
            }
            catch (IndexOutOfRangeException ie)
            {
                Debug.WriteLine(ie.StackTrace);
                this.lstItems.ItemsSource = null;
            }
            catch (Exception ex)
            {
                this.synth.Speak("出现错误");
                this.tbResult.Background = Brushes.Red;
                this.tbResult.Text = ex.Message;
                this.AppendText(ex.Message + Environment.NewLine + ex.StackTrace);
                this.lstItems.ItemsSource = null;
            }
            finally
            {
                this.tbDeliveryNumber.Text = "";
                this.chkIngoreWeightDetect.IsChecked = false;
            }
        }

        private void btnDetail_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button btn = sender as Button;
                if (btn == null || btn.DataContext == null || btn.DataContext is Mengsk.ProxyDelivery.Domain.Order == false)
                {
                    return;
                }
                OrderDetailWindow window = new OrderDetailWindow { DataContext = btn.DataContext };
                window.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnDeliveryNumber_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button btn = sender as Button;
                if (btn == null || btn.DataContext == null || btn.DataContext is Mengsk.ProxyDelivery.Domain.Order == false)
                {
                    return;
                }
                var order = btn.DataContext as Mengsk.ProxyDelivery.Domain.Order;
                Delivery.DeliveryQueryWindow window = new Delivery.DeliveryQueryWindow { DeliveryCompany = order.DeliveryCompany, DeliveryNumber = order.DeliveryNumber };
                window.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private void btnClearHistory_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MessageBox.Show("是否清空当前记录?", "确定", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                {
                    return;
                }
                this.scanedViewModels.Clear();
                this.tbTotal.Text = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        #region 圆通金刚系统导航控制

        private void btnInject_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.wb1.InvokeScript("myInjectMac");
                this.wb1.InvokeScript("fixahref");
                string macId = "visitorMac";
                HTMLDocument doc2 = this.wb1.Document as HTMLDocument;
                var item = doc2.getElementById(macId) as IHTMLInputHiddenElement;
                if (item != null)
                {
                    Console.WriteLine(item.value);
                }
                MessageBox.Show("注入成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "注入失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnBack_Click(object sender, RoutedEventArgs e)
        {
            if (this.wb1.CanGoBack)
            {
                this.wb1.GoBack();
            }
        }

        private void btnForward_Click(object sender, RoutedEventArgs e)
        {
            if (this.wb1.CanGoForward)
            {
                this.wb1.GoForward();
            }
        }

        private string QueryOrderId(string ppcod)
        {
            var obj = this.wb1.InvokeScript("mengsk_search_ppcod", ppcod);
            string text = obj == null ? "" : obj.ToString();

            if (this.tbYTDebug.LineCount > 100000)
            {
                this.tbYTDebug.Text = "";
            }
            if (obj == null)
            {
                this.tbYTDebug.AppendText(DateTime.Now + ":JavaScript方法没有返回值");
                return "false";
            }
            else
            {
                //this.tbYTDebug.AppendText(DateTime.Now + ":" + text);
            }

            //从数据中提取物流公司对应的ID
            int ppcodIndex = text.LastIndexOf(ppcod);
            if (ppcodIndex < 0)
            {
                throw new Exception("无法根据PPCOD找到对应物流订单,当前COD编号:" + ppcod);
            }

            //向前搜索圆通公司的OrderID
            int lastIndex = -1;
            int currentIndex = 0;
            while (currentIndex < ppcodIndex)
            {
                currentIndex = text.IndexOf("orderId", currentIndex);
                if (currentIndex < 0)
                {
                    break;
                }
                Debug.WriteLine(text.Substring(currentIndex, 50));
                if (currentIndex >= ppcodIndex)
                {
                    break;
                }
                lastIndex = currentIndex;
                currentIndex += "orderId".Length;
            }

            if (lastIndex < 0)
            {
                throw new Exception("无法根据PPCOD找到对应物流订单,当前COD编号:" + ppcod);
            }

            //找到了
            int spaceIndex = text.IndexOf("\"", lastIndex + "orderId=\"".Length);
            if (spaceIndex < 0)
            {
                throw new Exception("返回数据有错误,无法找到\"结束符");
            }

            string orderId = text.Substring(lastIndex + "orderId=\"".Length, spaceIndex - lastIndex - "orderId=\"".Length);
            return orderId;
        }


        #endregion


        private void AppendText(String message)
        {
            if (this.tbYTDebug.LineCount > 10000)
            {
                this.tbYTDebug.Clear();
            }
            this.tbYTDebug.AppendText(DateTime.Now + ":" + message);
        }

        private void btnGet_Click(object sender, RoutedEventArgs e)
        {
            string codNumber = this.tbCodNumber.Text.Trim().Replace(" ", "").Replace(":", "").Replace("：", "");

            if (string.IsNullOrWhiteSpace(codNumber))
            {
                MessageBox.Show("COD编号为空");
                return;
            }

            try
            {
                //获取物流编号
                string deliveryId = this.QueryOrderId(codNumber);
                this.AppendText("获取到的物流号:" + deliveryId);
                MessageBox.Show(deliveryId);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnMark_Click(object sender, RoutedEventArgs e)
        {
            string codNumber = this.tbCodNumber.Text.Trim().Replace(" ", "").Replace(":", "").Replace("：", "");

            if (string.IsNullOrWhiteSpace(codNumber))
            {
                MessageBox.Show("COD编号为空");
                return;
            }

            try
            {
                throw new Exception("功能未实现");
                //获取物流编号
                //string deliveryId = this.QueryOrderId(codNumber);

                //if (string.IsNullOrWhiteSpace(deliveryId) || deliveryId.Length < 8)
                //{
                //    this.tbYTDebug.AppendText(DateTime.Now + ":最终获取物流编号失败,获取到的数据:" + deliveryId);
                //    throw new Exception("最终获取物流编号失败");
                //}

                //object ret = this.wb1.InvokeScript("mengsk_markdelivery", deliveryId, number);
                //if (ret == null)
                //{
                //    throw new Exception("发货标记失败,JS返回值为空");
                //}

                //string strRet = ret.ToString();
                //if (strRet.Equals("SUCCESS", StringComparison.OrdinalIgnoreCase) == false)
                //{
                //    throw new Exception(strRet);
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

    }
}
